/**
 * 公共Model
 */
import { Platform } from "react-native";

import { getStore, setStore, unique } from "../utils";
import { buryingPoint } from "../services/public";

const trimAreasData = item => {
  const resData = {
    label: item.areaName,
    value: item.id,
  };
  if (Array.isArray(item.children) && item.children.length > 0) {
    resData.children = item.children.map(citem => trimAreasData(citem));
  }
  return resData;
};

const initData = {
  loading: false,
  userInfo: {},
  currentMenuName: "",
  goInStatus: "-1", // 记录第一次进入，每次重现进入APP后重制
  version: "1.0.1",
  containerHeight: 0,
  history: [],
  isLogin: false,
};

export default {
  namespace: "public",
  state: {
    ...initData,
  },

  effects: {
    // eslint-disable-next-line require-yield
    *saveStorage({ payload }) {
      getStore("history").then((res = []) => {
        if (res != null) {
          const temp = JSON.parse(res);
          temp.push(payload);
          const temp2 = unique(temp);
          console.log("after:", temp2);
          setStore("history", JSON.stringify(temp2));
        } else {
          const temp = [];
          temp.push(payload);
          setStore("history", JSON.stringify(temp));
        }
        return true;
      });
    },
    // eslint-disable-next-line require-yield
    *loadStorage({ put }) {
      getStore("history").then((res = []) => {
        if (res != null) {
          //  需要时间降序和去重
          const temp = JSON.parse(res);
          temp.reverse();
        }
      });
    },
    // eslint-disable-next-line require-yield
    *deleteStorage() {
      setStore("history", JSON.stringify([]));
      // removeStore("history");
    },
    // App 埋点
    *buryingPoint({ payload }, { call }) {
      const newdata = { ...payload, deviceType: Platform.OS === "ios" ? 1 : 0 };
      const res = yield call(buryingPoint, newdata);
      return res;
    },
    // eslint-disable-next-line require-yield
    *saveData({ payload }) {
      getStore("chatdata").then(res => {
        const temp = JSON.parse(res);
        console.log("@@@@", temp);

        if (Array.isArray(temp) && temp.length > 0) {
          // 根据用户手机号去保存json  eg: [{curid:id,data:jsonstr}]
          // 获取当前用户的记录
          for (let index = 0; index < temp.length; index += 1) {
            const iterator = temp[index];
            if (iterator.curid === payload.curid) {
              const currentRecordStr = iterator.data;
              const currentRecord = JSON.parse(currentRecordStr);
              currentRecord.push(payload);
              //  转成jsonstr
              const jsonStr = JSON.stringify(currentRecord);

              temp[index] = { curid: payload.curid, data: jsonStr };
              setStore("chatdata", JSON.stringify(temp));
              return;
            }
          }
          console.log("%%%%");

          const currentRecord = [];
          currentRecord.push(payload);
          //  转成jsonstr
          const jsonStr = JSON.stringify(currentRecord);

          temp.push({ curid: payload.curid, data: jsonStr });

          console.log(JSON.stringify(temp));
          setStore("chatdata", JSON.stringify(temp));
        } else {
          const temp2 = [];
          const currentRecord = [];
          currentRecord.push(payload);
          //  转成jsonstr
          const jsonStr = JSON.stringify(currentRecord);

          temp2.push({ curid: payload.curid, data: jsonStr });

          console.log(JSON.stringify(temp2));
          setStore("chatdata", JSON.stringify(temp2));
        }
        return true;
      });
    },
    // eslint-disable-next-line require-yield
    *updateData({ payload }) {
      getStore("chatdata").then(res => {
        const temp = JSON.parse(res);

        if (Array.isArray(temp) && temp.length > 0) {
          // 根据用户手机号去保存json  eg: [{curid:id,data:jsonstr}]
          // 获取当前用户的记录
          for (let index = 0; index < temp.length; index += 1) {
            const iterator = temp[index];
            if (iterator.curid === payload[0].curid) {
              // const currentRecordStr = iterator.data;
              // currentRecord.push(payload);
              //  转成jsonstr
              const jsonStr = JSON.stringify(payload);
              temp[index] = { curid: iterator.curid, data: jsonStr };

              setStore("chatdata", JSON.stringify(temp));
              return;
            }
          }
        }
        return true;
      });
    },
    // eslint-disable-next-line require-yield
    *deleteData() {
      setStore("chatdata", JSON.stringify([]));
      setStore("setRecType", "putonghua");
      // removeStore("history");
    },
  },
  reducers: {
    clear: () => ({
      ...initData,
    }),
    "save/loadStorage": (state, { payload }) => ({
      ...state,
      history: payload,
    }),
    checklogin: (state, { payload }) => ({
      ...state,
      isLogin: payload.isLogin,
    }),
  },
};
